<?php
/**
 * Booking Controller for RoomBooking Component
 * 
 * @version 1.0
 * @package    Joomla
 * @subpackage RoomBooking
 * @copyright (C) 2011 Giovanni Marzulli
 * @license		GNU/GPL
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );


class RoomBookingControllerBooking extends RoomBookingController
{
	
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

		// Register Extra tasks
		$this->registerTask( 'add' , 'edit' );
		$this->registerTask( 'apply' , 'save' );
	}
	
	/**
	 * Method to display the view
	 * @return void
	 */
	 function display()
    {
		$modelRoom =& $this->getModel('room');
		$modelRooms =& $this->getModel('rooms');
		$modelBuilding =& $this->getModel('building');
                $modelBookings =& $this->getModel('bookings');
                $view = $this->getView('booking','html');
		$view->setModel($modelBuilding);
		$view->setModel($modelRoom);
		$view->setModel($modelRooms);
                $view->setModel($modelBookings);
		parent::display();
    }
	
	/**
	 * display the edit form
	 * @return void
	 */
	function edit()
	{
		JRequest::setVar( 'view', 'booking' );
		JRequest::setVar( 'layout', 'form'  );
		JRequest::setVar('hidemainmenu', 1);

		$this->display();
	}
	
/**
	 * 
	 */
	function save(){
		
		$repeat = JRequest::getVar('repeat_type');
		$series = $this->store();
		$i=0;
		if ($repeat!="0" && isset($series))
		{
			JRequest::setVar('series',$series);
			JRequest::setVar('id',$series);
			$this->store();
			JRequest::setVar('id',0);
			$start=new DateTime(JRequest::getVar('start_date'));
			$end=new DateTime(JRequest::getVar('end_date'));
			$until=new DateTime(JRequest::getVar('repeat_until'));
			while ($until>$start){
				switch($repeat){
					case "day":{
						$start->modify("+1 days");
						$end->modify("+1 days");
				 		break;		
					}
					case "week":{
						$start->modify("+7 days");
						$end->modify("+7 days");
				 		break;
					}
					case "2week":{
						$start->modify("+14 days");
						$end->modify("+14 days");
				 		break;
					}
					case "month":{
						$start->modify("+1 months");
						$end->modify("+1 months");
					 	break;
					}
					case "year":{
						$start->modify("+1 years");
						$end->modify("+1 years");
				 		break;
					}
				}
			JRequest::setVar('start_date',$start->format('Y-m-d'));
			JRequest::setVar('end_date',$end->format('Y-m-d'));
//                        echo $start->format('Y-m-d').'-'.$end->format('Y-m-d');
			if ($until>=$start){
				$return = $this->store();
				if ($return==0)
					$i++;	
			}
		}
		if ($i!=0)
		{
			$msg = JText::_( 'SERIESSAVED' ).': '.$i.' '.JText::_( 'BOOKSNOSAVED' );
			$type='notice';
			if ($this->getTask()=='apply')
				$link ='index.php?option=com_roombooking&controller=booking&task=edit&cid='.$series;
			else
				$link = 'index.php?option=com_roombooking&view=bookings';
			$this->setRedirect($link, $msg, $type);
		}
	}
}
	
	/**
	 * save a record and redirect 
	 * @return void
	 */	
	function store()
	{
		JRequest::setVar('start',JRequest::getVar('start_date').' '.JRequest::getVar('start_hour').':'.JRequest::getVar('start_minute'));
		JRequest::setVar('end',JRequest::getVar('end_date').' '.JRequest::getVar('end_hour').':'.JRequest::getVar('end_minute'));
		$booking = JRequest::get('POST');
		if ($booking['short_description'] && $booking['start'] && $booking['end'] && $booking['id_room'] && $booking['id_user']) {
		$available = $this->roomAvailable($booking['start'],$booking['end'],$booking['id_room'],$booking['id']);
		if ($available==1){
			$model = $this->getModel('booking');
			if ($returnid == $model->store($post)) {
				$msg = JText::_( 'BOOKSAVED' );
				$type='message';
				
			} else {
				$msg = JText::_( 'SAVEBOOKERROR');
				$type='error';
			}
		} else {
				if ($available==0)
            	  		$msg = JText::_( 'ROOMBUSY' );
            	else if ($available==-1)
            	  		$msg = JText::_( 'NOCLOSINGTIME' ); 
            	  	
            	$return=$available;
				$id = JRequest::getVar('id');
				$type='error';
			}
		}
		else {
			$msg = JText::_( 'FIELDMISSING' );
			$type='error';
		}
			
		if ($this->getTask()=='apply')
			$link ='index.php?option=com_roombooking&controller=booking&task=edit&cid='.$returnid;
		else
			$link = 'index.php?option=com_roombooking&view=bookings';
		$this->setRedirect($link, $msg, $type);
		
		return $returnid;
	}
	

	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
		$model = $this->getModel('booking');
		if(!$model->delete()) {
			$msg = JText::_( 'NOBOOKINGSDELETE' );
			$type='error';
		} else {
			$msg = JText::_( 'BOOKINGSDELETE' );
			$type='message';
		}

		$this->setRedirect( 'index.php?option=com_roombooking&view=bookings', $msg ,$type);
	}
	
	/**
	 * remove series
	 * @return void
	 */
	function removeSeries()
	{
		$series = JRequest::getVar('series');
		$id_booking = JRequest::getVar('id');
		$id_room= JRequest::getVar('id_room');
		
		//check user privileges
		$params = &JComponentHelper::getParams( 'com_roombooking' );        
		$model = $this->getModel('booking');
		if(!$model->deleteSeries($series)) {
				$msg = JText::_( 'NOSERIESINGDELETE' );
				$link = 'index.php?option=com_roombooking&view=booking&layout=form&cid='.$id_booking;
				$type='error';
			} else {
				$msg = JText::_( 'SERIESDELETE' );
				$link = 'index.php?option=com_roombooking&view=bookings&id_room='.$id_room;
				$type='message';
			}
			$this->setRedirect($link, $msg, $type);
		}
		

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_( 'OPERCANC' );
		$this->setRedirect( 'index.php?option=com_roombooking&view=bookings', $msg );
	}
	
	
	/**
	 * verify the room availability
	 * @return mixed
	 */
	function roomAvailable($start, $end, $id_room,$id_booking){
		JLoader::import( 'room', JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' );
		$modelRoom =& JModel::getInstance( 'room', 'RoomBookingModel' );
		$id_building = $modelRoom->getIdBuildOfRoom($id_room);
		JLoader::import( 'building', JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' );
		$modelBuilding =& JModel::getInstance( 'building', 'RoomBookingModel' );
		
		$opening = new DateTime($start);
		$closing = new DateTime($end);
		$start = new DateTime($start);
		$end = new DateTime($end);
		$today = new DateTime('now');
		
		$we_opening = $modelBuilding->getWEOpening($id_building);
		if ($we_opening == 0 && ($end->format('N') == 6 || $end->format('N') == 7 || $start->format('N') == 6 || $start->format('N') == 7) )
			return JText::_( 'NOSUNSAT' );
		$times = $modelBuilding->getBuildOpenCloseTime($id_building);
		
		$times->opening = explode(':', $times->opening);
		$opening->setTime($times->opening[0], $times->opening[1]);
		$times->closing = explode(':', $times->closing);
		$closing->setTime($times->closing[0], $times->closing[1]);
		
		if($start>=$opening && $end<=$closing) 
		{
			$modelBookings =& $this->getModel('bookings');
			$bookings =& $modelBookings->getRoomBookings($id_room, $id_booking);			
		
			foreach ($bookings as $booking){
				$start_booking = new DateTime($booking->start);
				$end_booking = new DateTime($booking->end);
				if (($start>=$start_booking && $start<$end_booking) ||
			   		($start<$start_booking && $end>$start_booking))
						return 0;
			}
			return 1;
		}
		else
			return -1;		
	}
	
	
}
